package com.nut;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.Base64Codec;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ author : HyoJoo-W
 * @ createDate : 2021-05-11 14:10
 * @ Description : token过期校验
 */
@SpringBootTest
public class ExpireJwt
{
    @Test
    public void testCreateTokenExpire()
    {
        //当前系统时间
        long now = System.currentTimeMillis();
        //失效时间
        long exp = now + 60 * 1000;

        //创建JwtBuilder对象
        JwtBuilder jwtBuilder = Jwts.builder()
                //声明的标识
                .setId("8888")
                //主体subject
                .setSubject("Rose")
                //创建日期
                .setIssuedAt(new Date())
                //签名
                .signWith(SignatureAlgorithm.HS256, "xxxx")
                //设置失效时间
                .setExpiration(new Date(exp));
        //获取Jwt的token
        String token = jwtBuilder.compact();
        System.out.println("token = " + token);

        System.out.println("===========================");
        String[] split = token.split("\\.");
        System.out.println("头部Base64解码后:");
        System.out.println(Base64Codec.BASE64.decodeToString(split[0]));
        System.out.println("载荷Base64解码后:");
        System.out.println(Base64Codec.BASE64.decodeToString(split[1]));
        System.out.println("签名解码后:");
        System.out.println(Base64Codec.BASE64.decodeToString(split[2]));
    }

    @Test
    public void testParseTokenExpire()
    {
        String token =
                "eyJhbGciOiJIUzI1NiJ9" +
                        ".eyJqdGkiOiI4ODg4Iiwic3ViIjoiUm9zZSIsImlhdCI6MTYyMDcxMzgyMywiZXhwIjoxNjIwNzEzODgzfQ" +
                        ".lI9G572peueZxLz3tUL90ZQooajCMKVkbmRmFvIO7nA";
        Claims claims = Jwts.parser()
                .setSigningKey("xxxx")
                .parseClaimsJws(token)
                .getBody();

        System.out.println("claims.getId() = " + claims.getId());
        System.out.println("claims.getSubject() = " + claims.getSubject());
        System.out.println("claims.getIssuedAt() = " + claims.getIssuedAt());

        //token过期校验
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("签发时间" + format.format(claims.getIssuedAt()));
        System.out.println("过期时间" + format.format(claims.getExpiration()));
        System.out.println("当前时间" + format.format(new Date()));


    }


}
